import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:
 * @title: SyncAndReentrantLockDemo
 * @author: zp
 * @date: 2021/8/2 21:05
 * 三个线程 按顺序打印
 * 循环10次
 */
class ShareResource {
    private int num = 1;
    private final Lock lock = new ReentrantLock();
    private final Condition conditionA = lock.newCondition();
    private final Condition conditionB = lock.newCondition();
    private final Condition conditionC = lock.newCondition();

    public void putNum5() {
        lock.lock();
        try {
            while (num != 1) {
                conditionA.await();
            }
            for (int i = 1; i <= 5; i++) {
                System.out.println(i);
            }
            num++;
            conditionB.signal();
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void putNum10() {
        lock.lock();
        try {
            while (num != 2) {
                conditionB.await();
            }
            for (int i = 1; i <= 10; i++) {
                System.out.println(i);
            }
            num++;
            conditionC.signal();
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void putNum15() {
        lock.lock();
        try {
            while (num != 3) {
                conditionC.await();
            }
            for (int i = 1; i <= 15; i++) {
                System.out.println(i);
            }
            num = 1;
            conditionA.signal();
        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

/**
 * @description:
 * @author: zp
 * @date: 2021/8/5 21:00
 * @param: null
 * @return:
 */
public class SyncAndReentrantLockDemo {
    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                shareResource.putNum5();
            }, "A").start();

            new Thread(() -> {
                shareResource.putNum10();
            }, "B").start();

            new Thread(() -> {
                shareResource.putNum15();
            }, "C").start();
        }

    }
}
